package com.yixia.pea.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yixia.common.annotation.DataScope;
import com.yixia.common.constant.UserConstants;
import com.yixia.common.core.domain.entity.SysUser;
import com.yixia.common.exception.ServiceException;
import com.yixia.common.utils.SecurityUtils;
import com.yixia.common.utils.StringUtils;
import com.yixia.common.utils.bean.BeanUtils;
import com.yixia.common.utils.spring.SpringUtils;
import com.yixia.pea.constant.FinishStatus;
import com.yixia.pea.constant.RatingStatus;
import com.yixia.pea.constant.ScoreStatus;
import com.yixia.pea.domain.credit.PeaCreScore;
import com.yixia.pea.domain.credit.PeaScore;
import com.yixia.pea.domain.dto.PeaScoreDto;
import com.yixia.pea.mapper.PeaCreScoreMapper;
import com.yixia.pea.mapper.PeaHzFamMapper;
import com.yixia.pea.domain.credit.PeaHzBase;
import com.yixia.pea.domain.credit.PeaHzFam;
import com.yixia.pea.domain.dto.PeaHzBaseDto;
import com.yixia.pea.service.PeaHzBaseService;
import com.yixia.pea.mapper.PeaHzBaseMapper;
import com.yixia.pea.service.PeaScoreService;
import com.yixia.pea.utils.ScoreUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author 35038
* @description 针对表【pea_hz_base】的数据库操作Service实现
* @createDate 2023-09-01 08:07:04
*/
@Service
public class PeaHzBaseServiceImpl extends ServiceImpl<PeaHzBaseMapper, PeaHzBase>
    implements PeaHzBaseService{

    @Autowired
    private PeaHzBaseMapper hzBaseMapper;
    @Autowired
    private PeaHzFamMapper hzFamMapper;
    @Autowired
    private PeaScoreService peaScoreService;
    @Autowired
    private PeaCreScoreMapper creScoreMapper;

    /**
     * 验证该户主是否已经存在
     * @param hzBase 户主信息
     * @return 结果
     */
    @Override
    public boolean checkIdCardNumUnique(PeaHzBase hzBase) {
        Long hzId = StringUtils.isNull(hzBase.getHzId()) ? -1L : hzBase.getHzId();
        PeaHzBase info = hzBaseMapper.checkIdCardNumUnique(hzBase.getHzIdCardNumber());
        if (StringUtils.isNotNull(info) && info.getHzId().longValue() != hzId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }


    /**
     * 验证该户主是否已经存在
     * @param hzBase 户主信息
     * @return 结果
     */
    @Override
    public boolean checkPhoneNumberNumUnique(PeaHzBase hzBase) {
        Long hzId = StringUtils.isNull(hzBase.getHzId()) ? -1L : hzBase.getHzId();
        PeaHzBase info = hzBaseMapper.checkPhoneNumberNumUnique(hzBase.getHzPhoneNumber());
        if (StringUtils.isNotNull(info) && info.getHzId().longValue() != hzId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }


    /**
     * 校验用户是否有数据权限
     *
     * @param hzId 户主id
     */
    @Override
    public void checkPeaDataScope(Long hzId) {
        /*1. 是管理员就一定有该权限, 不是超级管理员就判断里面的数据能不能修改*/
        if(!SysUser.isAdmin(SecurityUtils.getUserId())) {
            /*不是就进行查询*/
            PeaHzBaseDto hzBaseDto = new PeaHzBaseDto();
            hzBaseDto.setHzId(hzId);
            List<PeaHzBaseDto> info = SpringUtils.getAopProxy(this).selectListPage(hzBaseDto);
            /*没查找到抛出异常不存在*/
            if (StringUtils.isNull(info))
            {
                throw new ServiceException("没有权限访问该数据！");
            }
        }

    }


    /**
     * 新增农户信息
     * @param peaHzBaseDto 农户信息
     * @return 结果
     */
    @Override
    @Transactional
    public boolean insertPeaHzBase(PeaHzBaseDto peaHzBaseDto) {
        // 直接将收集到的信息放到农户信息表中
        int insert = hzBaseMapper.insert(peaHzBaseDto);
        // 再把家庭成员信息进行添加
        Long hzId = peaHzBaseDto.getHzId();
        List<PeaHzFam> peaHzFamList = peaHzBaseDto.getPeaHzFamList();
        if(StringUtils.isNotEmpty(peaHzFamList)) {
            for (PeaHzFam peaHzFam : peaHzFamList) {
                peaHzFam.setHzId(hzId);
            }
            int i = hzFamMapper.insertPeaHzFam(peaHzFamList);
        }
        return true;
    }

    /**
     * 修改农户信息
     * @param peaHzBaseDto 农户信息
     * @return 结果
     */
    @Override
    @Transactional
    public int editPeaHzBase(PeaHzBaseDto peaHzBaseDto){
        // 先修改农户基本表的信息
        int row1 = hzBaseMapper.updateById(peaHzBaseDto);
        // 再修改家庭成员表（删除重新建）
        Long hzId = peaHzBaseDto.getHzId();
        int row2 = hzFamMapper.deleteHzFamsByHzId(hzId);
        List<PeaHzFam> peaHzFamList = peaHzBaseDto.getPeaHzFamList();
        peaHzFamList = peaHzFamList.stream().peek(item -> item.setHzId(hzId)).collect(Collectors.toList());
        int i = hzFamMapper.insertPeaHzFam(peaHzFamList);
        return row2 + row1 + i;
    }


    /**
     * 分页查询
     * @param peaHzBaseDto 查询条件
     * @return 查询给结果
     */
    @DataScope(userAlias = "u", deptAlias = " d")
    public List<PeaHzBaseDto> selectListPage(PeaHzBaseDto peaHzBaseDto){
        return hzBaseMapper.selectListPage(peaHzBaseDto);
    }


    /**
     * 根据hzId进行查询查询
     * @param hzId 户主ID
     * @return 返回结果
     */
    public PeaHzBaseDto selectPeaBaseById(Long hzId){
        // 1. 先将户主的基本信息查询出来
        PeaHzBase hzBase = this.getById(hzId);
        PeaHzBaseDto hzBaseDto = new PeaHzBaseDto();
        BeanUtils.copyProperties(hzBase, hzBaseDto);
        // 2. 再根据户主Id查询出家庭成员信息
        List<PeaHzFam> list = hzFamMapper.selectFamsByHzId(hzId);
        hzBaseDto.setPeaHzFamList(list);
        return hzBaseDto;
    }

    /**
     * 开始评分
     * @param hzId 户主ID
     * @return 返回结果
     */
    @Override
    public int startScoring(Long hzId) {
        return hzBaseMapper.startScoring(hzId);
    }

    // 根据ID修改评分状态
    @Override
    public int updateRatingStatus(Long hzId) {
        LambdaUpdateWrapper<PeaHzBase> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(PeaHzBase::getRatingStatus, RatingStatus.COM_SCORING);
        updateWrapper.eq(PeaHzBase::getHzId, hzId).eq(PeaHzBase::getDelFlag, "0");
        return hzBaseMapper.update(null, updateWrapper);
    }


    // 将评分状态改成未评分
    @Override
    public int resfreshRatingStatus(Long[] hzIds){
        return hzBaseMapper.resfreshRatingStatus(hzIds);
    }


    // 对这些户主进行定向信用评分
    @Override
    @Transactional
    public void creidtScoring(Long[] hzIds){
        // 检查这些hzId的数据权限是否存在
        for (Long hzId : hzIds) {
            PeaHzBase hzBase = hzBaseMapper.selectById(hzId);
            if(!StringUtils.isNotEmpty(hzBase)){
                throw new ServiceException("编号为'" + hzId + "'农户数据不存在！");
            }else if(!hzBase.getRatingStatus().equals(RatingStatus.COM_SCORING)){
                throw new ServiceException("编号为'" + hzId + "'农户评分未完成，不能进行定向评分！");
            }
        }
        // 进行评分
        for (Long hzId : hzIds) {
            // 获取户主信息
            PeaHzBase hzBase = selectPeaBaseById(hzId);
            // 获取评分信息
            List<PeaScoreDto> peaScores = peaScoreService.selectScoreByHzId(hzId);

            // 创建评分对象
            PeaCreScore creScore = new PeaCreScore();

            creScore.setHzId(hzId);


            // 劳动状态评分
            BigDecimal decimal = ScoreUtils.laoDongLiScore(Integer.parseInt(hzBase.getFamilyLoaderSize()), Integer.parseInt(hzBase.getFamilySize()));
            creScore.setLaderScore(decimal);
            // 家庭产业评分
            BigDecimal decimal1 = ScoreUtils.famCyScore(hzBase);
            creScore.setFamCyScore(decimal1);
            // 家庭人均收入评分
            BigDecimal decimal2 = ScoreUtils.famNumScore(hzBase);
            creScore.setFamNumScore(decimal2);
            // 定性评分
            BigDecimal row = new BigDecimal(0);
            for (PeaScoreDto peaScore : peaScores) {
                BigDecimal decimal3 = ScoreUtils.dingXinScore(peaScore);

                if(decimal3.compareTo(new BigDecimal(0)) == 0){
                    // 有涉毒情况
                    row = new BigDecimal(0);
                    break;
                }
                row = row.add(decimal3.divide(new BigDecimal(400)));
            }
            // 涉毒情况
            if(row.compareTo(new BigDecimal(0)) == 0){
                creScore.setCreditScore("该农户有涉黑情况！");
                creScore.setDingXinScore(row);
                //creScoreMapper.insert(creScore);
            }else {

                // 将分数存入
                creScore.setDingXinScore(row.divide(new BigDecimal(5)));

                // 信用评分
                BigDecimal decimal3 = ScoreUtils.creditScore(creScore);
                creScore.setCreditScore(String.valueOf(decimal3));


                // 进行信用等级评分
                String s = ScoreUtils.creditDanger(creScore);
                creScore.setCreditDarge(s);
                // 插入数据
                //creScoreMapper.insert(creScore);
            }

            // 进行查询看是否已经添加
            PeaCreScore info = creScoreMapper.selectByHzId(hzId);
            if(StringUtils.isNotEmpty(info)){
                creScore.setScId(info.getScId());
                creScoreMapper.updateById(creScore);
            }else {
                creScoreMapper.insert(creScore);
            }

            // 将评分状态和完成情况变成完成
            PeaHzBase hzBaseInfo = new PeaHzBase();
            hzBaseInfo.setHzId(hzId);
            hzBaseInfo.setFinishStatus(FinishStatus.YES);
            hzBaseInfo.setScoreStatus(ScoreStatus.YES);
            hzBaseMapper.updateById(hzBaseInfo);
        }
    }
}




